package com.sos.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
@RequiredArgsConstructor
@Slf4j
public class MailService {

    private final JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;  // 从配置文件获取发件人邮箱

    /**
     * 发送验证码邮件（使用MimeMessage确保发件人正确设置）
     */
    public void sendVerificationCode(String toEmail, String code) {
        try {
            // 使用MimeMessage替代SimpleMailMessage
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            // 明确设置发件人（必须与配置文件中的username一致）
            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject("sos密码重置验证码");
            helper.setText("您的密码重置验证码为: " + code + "，有效期3分钟，请尽快使用。");

            mailSender.send(message);
            log.info("邮件发送成功，收件人: {}", toEmail);
        } catch (MessagingException e) {
            log.error("发送邮件失败，收件人: {}，错误: {}", toEmail, e.getMessage());
            // 不抛出异常，避免影响主流程
        }
    }

}